package comp.wxapi.service;

import java.net.URLDecoder;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;

import comp.wxapi.bean.BaseConfigBean;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;

@Service
public class EventService {
	
	private static final Logger logger = LoggerFactory.getLogger(EventService.class);
	
	@Autowired
	private MessageRouterService messageRouterService;
	
	public String eventService(BaseConfigBean baseConfigBean,String data) {
		String result = "";
		try {
			//公众号首次推送事件验证
			WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(baseConfigBean.getToken(), baseConfigBean.getEncodingAESKey(),baseConfigBean.getAppid());
			if(StringUtils.isNotBlank(baseConfigBean.getEchostr())) {
				if(baseConfigBean.isAes()) {
					result = wxBizMsgCrypt.verifyUrl(baseConfigBean.getMsg_signature(), baseConfigBean.getTimestamp(), baseConfigBean.getNonce(), URLDecoder.decode(baseConfigBean.getEchostr(),"utf-8"));
				}else {
					result = baseConfigBean.getEchostr();
				}
				return result;
			}
			String xmlData = "";
			if(baseConfigBean.isAes()) {
					xmlData = wxBizMsgCrypt.decryptMsg(baseConfigBean.getMsg_signature(), baseConfigBean.getTimestamp(), baseConfigBean.getNonce(), data);
			}else {
				xmlData = data;
			}
			//事件消息解析
			WxMpXmlMessage wxMpXmlMessage = WxMpXmlMessage.fromXml(xmlData);
			logger.info("微信推送事件内容:\n{}",JSON.toJSONString(wxMpXmlMessage));
			result = messageRouterService.messageRouter(wxMpXmlMessage);
			logger.info("【响应微信消息】\n{}",result);
			if(StringUtils.isNotEmpty(result) && baseConfigBean.isAes()) {
				result = wxBizMsgCrypt.encryptMsg(result, baseConfigBean.getTimestamp(), baseConfigBean.getNonce());
			}else if(StringUtils.isEmpty(result)) {
				result = "";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}	
		return result;
	}
	
}
